import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { CustomLoggerService } from './logger/custom-logger.service';
import { SecurityMonitorService } from './security/security-monitor.service';

async function bootstrap() {
  // 创建Winston日志器
  const logger = WinstonModule.createLogger({
    level: process.env.LOG_LEVEL || 'info',
    format: winston.format.combine(
      winston.format.timestamp(),
      winston.format.errors({ stack: true }),
      winston.format.json(),
    ),
    transports: [
      new winston.transports.Console({
        format: winston.format.combine(
          winston.format.colorize(),
          winston.format.simple(),
        ),
      }),
      new winston.transports.File({
        filename: 'logs/error.log',
        level: 'error',
        maxsize: 10485760, // 10MB
        maxFiles: 5,
      }),
      new winston.transports.File({
        filename: 'logs/combined.log',
        maxsize: 10485760, // 10MB
        maxFiles: 10,
      }),
    ],
  });

  const app = await NestFactory.create(AppModule, {
    logger,
    bufferLogs: true,
  });

  const configService = app.get(ConfigService);

  // 安全中间件配置
  app.use(helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        styleSrc: ["'self'", "'unsafe-inline'"],
        scriptSrc: ["'self'"],
        imgSrc: ["'self'", "data:", "https:"],
      },
    },
    hsts: {
      maxAge: 31536000,
      includeSubDomains: true,
      preload: true,
    },
  }));

  // CORS配置 - 零容忍安全策略
  const allowedOrigins = configService.get<string>('ALLOWED_ORIGINS', 'http://localhost:8101')
    .split(',')
    .map(origin => origin.trim());

  app.enableCors({
    origin: allowedOrigins,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: [
      'Origin',
      'X-Requested-With',
      'Content-Type',
      'Accept',
      'Authorization',
      'Cache-Control',
      'X-API-Key',
    ],
    credentials: true,
    maxAge: configService.get<number>('CORS_MAX_AGE', 86400),
    preflightContinue: false,
    optionsSuccessStatus: 204,
  });

  // 全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );

  // 请求体大小限制
  app.useBodyParser('json', { limit: '10mb' });
  app.useBodyParser('urlencoded', { limit: '10mb', extended: true });

  // API前缀
  app.setGlobalPrefix('api/v1');

  // 启动安全监控服务
  const securityMonitor = app.get(SecurityMonitorService);
  await securityMonitor.start();

  // Swagger文档配置 (仅在开发环境)
  if (configService.get<string>('NODE_ENV') === 'development') {
    const config = new DocumentBuilder()
      .setTitle('UC内镜评分系统 API')
      .setVersion('2.0.0')
      .setDescription('零隐患MFIS规范实现的安全API文档')
      .addTag('auth', '认证相关')
      .addTag('scoring', '评分相关')
      .addTag('health', '健康检查')
      .addBearerAuth()
      .build();

    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('api/docs', app, document);

    logger.log('📚 Swagger文档已启用: /api/docs');
  }

  // 优雅关闭处理
  const gracefulShutdown = async (signal: string) => {
    logger.log(`收到 ${signal} 信号，开始优雅关闭...`);

    try {
      // 停止接受新连接
      app.enableShutdownHooks();

      // 关闭安全监控
      await securityMonitor.stop();

      // 关闭应用
      await app.close();

      logger.log('✅ 应用已优雅关闭');
      process.exit(0);
    } catch (error) {
      logger.error('关闭过程中发生错误', error);
      process.exit(1);
    }
  };

  process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
  process.on('SIGINT', () => gracefulShutdown('SIGINT'));

  // 未捕获异常处理
  process.on('uncaughtException', (error) => {
    logger.error('未捕获异常', error);
    process.exit(1);
  });

  process.on('unhandledRejection', (reason, promise) => {
    logger.error('未处理的Promise拒绝', { reason, promise });
    process.exit(1);
  });

  // 启动服务器
  const port = configService.get<number>('PORT', 4000);
  const host = configService.get<string>('HOST', '0.0.0.0');

  await app.listen(port, host);

  logger.log(`🚀 UC内镜评分系统已启动`);
  logger.log(`📍 服务地址: http://${host}:${port}`);
  logger.log(`🌍 环境: ${configService.get<string>('NODE_ENV')}`);
  logger.log(`🔒 零隐患MFIS规范: 已激活`);

  if (configService.get<string>('NODE_ENV') === 'production') {
    logger.warn('⚠️  生产环境模式 - 安全监控已启用');
  }
}

// 零容忍策略：启动失败立即终止
bootstrap().catch((error) => {
  console.error('🚨 CRITICAL: 应用启动失败', error);
  process.exit(1);
});